package pub.doric.extension;

import com.github.pengfeizhou.jscore.JSExecutor;

import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicBoolean;

import pub.doric.DoricContext;
import pub.doric.DoricNativeDriver;
import pub.doric.IDoricDriver;
import pub.doric.engine.DoricJSEngine;
import pub.doric.engine.DoricNativeJSExecutor;
import pub.doric.engine.IDoricJSE;
import pub.doric.plugin.DoricJavaPlugin;

public class SkiaPlugin extends DoricJavaPlugin {

    private static AtomicBoolean sInitialized = new AtomicBoolean(false);

    public SkiaPlugin(DoricContext doricContext) {
        super(doricContext);

        boolean result = sInitialized.compareAndSet(false, true);
        if (result) {
            IDoricDriver driver = doricContext.getDriver();
            if (driver instanceof DoricNativeDriver) {
                DoricNativeDriver nativeDriver = (DoricNativeDriver) driver;
                try {
                    Field jsEngineField = DoricNativeDriver.class.getDeclaredField("doricJSEngine");
                    jsEngineField.setAccessible(true);
                    DoricJSEngine doricJSEngine = (DoricJSEngine) jsEngineField.get(nativeDriver);
                    Field mDoricJSEField = DoricJSEngine.class.getDeclaredField("mDoricJSE");
                    mDoricJSEField.setAccessible(true);
                    IDoricJSE doricJSE = (IDoricJSE) mDoricJSEField.get(doricJSEngine);
                    if (doricJSE instanceof DoricNativeJSExecutor) {
                        Field mJSExecutorField = DoricNativeJSExecutor.class.getDeclaredField("mJSExecutor");
                        mJSExecutorField.setAccessible(true);
                        JSExecutor jsExecutor = (JSExecutor) mJSExecutorField.get(doricJSE);
                        assert jsExecutor != null;
                        jsExecutor.injectNativeFunction("skiaNativeCall", SkiaJNI.getNativeCall());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
